<?php

namespace App\Models;

use  App\Models\FhCategory;
use Illuminate\Database\Eloquent\Model;

class FhProduct extends Model
{
	
    protected $table = 'fh_product';

    public static function boot()
    {
        parent::boot();

        static::saving(function ($model) {

            // $model->img = implode(",",$model->img);
            if(strpos($model->url, "/products/") === false){
                $model->url = "/products/".$model->url;
            }
        });
    }


    public function content()
    {
        return $this->hasMany('App\Models\FhProductContent','product_id','id');
    }

    public function list(){
        return $this->hasMany('App\Models\FhResourseList','product_id','id');
    }


    public function delete()
    {
        // 删除关联的 Comment
        $this->content()->delete();
        $this->list()->delete();    
        parent::delete();
    }


    public function getProductById($pid){
        $cate = FhCategory::where("pid",$pid)->where('show',1)->select('id','c_name')->get()->toArray();
        $product = [];
        if(!empty($cate)){
            $product[0]['title'] = FhCategory::where("id",$pid)->value('c_name');
            $product[0]['product'] = $this->where('pid',$pid)->where('show',1)->select('name','url','thumb','Introduction')->get()->toArray();
            foreach($cate as $k=>$v){
                $pro = $this->where('pid',$v['id'])->where('show',1)->select('name','url','thumb','Introduction')->get()->toArray();
                if(count($pro)>0){
                    $product[$k+1]['title'] = $v['c_name'];
                    $product[$k+1]['product'] = $pro;
                }
            }
        }else{
            $product[0]['title'] = FhCategory::where("id",$pid)->value('c_name');
            $product[0]['product'] = $this->where('pid',$pid)->where('show',1)->select('name','url','thumb','Introduction')->get()->toArray();
        }
        
        return $product;
    }
    
}
